package com.zty.utils.impl;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zty.BO.FileChunkMeta;
import com.zty.BO.MetaFile;
import com.zty.response.CommonResponse;
import com.zty.utils.ChunkAddressStrategy;
import com.zty.utils.ChunkDownloader;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author ZTY
 * @Description
 * @Date 18:04 2023-12-26
 **/

@Component
public class HttpChunkDownloader implements ChunkDownloader {

    private final ChunkAddressStrategy chunkAddressStrategy;

    private final RestTemplate restTemplate;

    private final ObjectMapper mapper;

    public HttpChunkDownloader(ChunkAddressStrategy chunkAddressStrategy, RestTemplate restTemplate, ObjectMapper mapper) {
        this.chunkAddressStrategy = chunkAddressStrategy;
        this.restTemplate = restTemplate;
        this.mapper = mapper;
    }

    @Override
    public byte[] download(FileChunkMeta chunkMeta) {
        //  获取地址
        String address = chunkAddressStrategy.get(chunkMeta);

        //  调用zty-chunk-server的read接口进行下载
        String url = address + "/file/read?filename={filename}&extension={extension}&chunkNo={chunkNo}&bucketName={bucketName}";

        Map<String, Object> params = new HashMap<>();
        params.put("extension",chunkMeta.getExtension());
        params.put("filename",chunkMeta.getFilename());
        params.put("chunkNo",chunkMeta.getChunkNo());
        params.put("bucketName",chunkMeta.getBucketName());

        //  发送请求
        Object response = restTemplate.getForObject(
                url,
                Object.class,
                params
        );
        CommonResponse<byte[]> commonResponse = mapper.convertValue(response, new TypeReference<CommonResponse<byte[]>>() {
        });
        return commonResponse.getData();
    }

    @Override
    public String schema() {
        return "http";
    }
}
